package hot;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class Num207 {
    public boolean canFinish(int numCourses, int[][] prerequisites) {
        int[] arr = new int[numCourses];
        List<List<Integer>> res = new ArrayList<>();
        Queue<Integer> queue = new LinkedList<>();
        for(int i = 0; i < numCourses; i++) {
            res.add(new ArrayList<>());
        }
        for(int[] nums : prerequisites) {
            arr[nums[0]]++;
            res.get(nums[1]).add(nums[0]);
        }
        for(int i = 0; i < numCourses; i++) {
            if (arr[i] == 0) queue.offer(i);
        }
            while(!queue.isEmpty()) {
                int pre = queue.poll();
                numCourses--;
                for(int num : res.get(pre)) {
                    if(--arr[num] == 0) queue.offer(num);
                }
            }
        return numCourses == 0;
    }
}
